package jnpf;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jnpf.base.UserInfo;
import jnpf.constant.GlobalConst;
import jnpf.consts.AuthConsts;
import jnpf.properties.SecurityProperties;
import jnpf.util.ServletUtil;
import jnpf.util.UserProvider;
import jnpf.utils.FeignHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 *
 * @date 2021/3/16 10:51
 */
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void apply(RequestTemplate template) {
        //添加token
        Map<String, String> headers = FeignHolder.get();
        String token = null;
        if(headers != null){
            //通过FeignHolder调用
            template.header("User-Agent", headers.get("user-agent"));
            template.header("Authorization", token = headers.get("authorization"));
            template.header("X-Real-IP", headers.get("x-real-ip"));
            template.header("X-Forwarded-For", headers.get("x-forwarded-for"));
                /*headers.entrySet().forEach((k)->{
                        template.header(k.getKey(), k.getValue());
                });*/
        }else {
            //先获取当前本地缓存中UserInfo的TOKEN
            //适配临时切换用户
            UserInfo userInfo = UserProvider.getLocalLoginUser();
            if(userInfo != null && userInfo.getToken() != null){
                token = userInfo.getToken();
                template.header("Authorization", token);
            }
            //Web环境直接调用
            HttpServletRequest request = ServletUtil.getRequest();
            if (request != null) {
                if(token == null) {
                    template.header("Authorization", request.getHeader("Authorization"));
                }
                template.header("User-Agent", request.getHeader("User-Agent"));
                template.header("X-Real-IP", request.getHeader("X-Real-IP"));
                template.header("X-Forwarded-For", request.getHeader("X-Forwarded-For"));
            }
        }
        if(securityProperties.isEnableInnerAuth() || securityProperties.isEnablePreAuth()) {
            template.header(AuthConsts.INNER_TOKEN_KEY, UserProvider.getInnerAuthToken());
        }
        template.header(GlobalConst.HEADER_HOST, ServletUtil.getRequestHost());
    }

    /**
     * Openfeign调用日志
     * NONE,BASIC,HEADERS,FULL共有四种等级
     * @return
     */
    @Bean
    Logger.Level feignLoggerLeave(){
        return Logger.Level.FULL;
    }
}
